<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="useDay">
        <el-date-picker clearable v-model="queryParams.useDay" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="线路" prop="routeId">
        <el-select v-model="queryParams.routeId" filterable placeholder="" @keyup.enter="handleQuery">
          <el-option v-for="item in routeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dispatch:schedulingDaily:add']">生成固定排班</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dispatch:schedulingDaily:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schedulingDailyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="true" />
      <el-table-column label="日期" align="center" prop="useDay" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.useDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线路" align="center" prop="routeName" />
      <el-table-column label="发车方案" align="center" prop="planName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleList(scope.row)"
            v-hasPermi="['dispatch:schedulingDailyTimetable:list']">排班管理</el-button>
          <el-button link type="primary" icon="List" @click="onlyShowFunc(scope.row)"
            v-hasPermi="['dispatch:schedulingDailyTimetable:list']">发车时刻表</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改排班对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="schedulingDailyRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="日期" prop="useDay">
              <el-date-picker clearable v-model="form.useDay" type="date" value-format="YYYY-MM-DD"
                :disabled-date="disabledDateFun" placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方案" prop="planId">
              <el-select v-model="form.planId" filterable placeholder="">
                <el-option v-for="item in planDatas" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 排班管理 -->
    <el-dialog :title="schedulingPlanTitle" v-model="schedulingPlanOpen" width="80%" append-to-body>
      <schedulingDailyTimetable :scheduling-id="schedulingId" :plan-id="schedulingPlanId" :only-show="onlyShow" />
    </el-dialog>
  </div>
</template>

<script setup name="SchedulingDaily">
import { listSchedulingDaily, getSchedulingDaily, delSchedulingDaily, addSchedulingDaily, updateSchedulingDaily, getPlanListByDay } from "@/api/dispatch/schedulingDaily";
import schedulingDailyTimetable from "./components/schedulingDailyTimetable.vue";
import { getRouteList } from "@/api/basic/route";

const { proxy } = getCurrentInstance();
const schedulingDailyList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const schedulingId = ref("")
const schedulingPlanId = ref("")
const planDatas = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    useDay: undefined,
    routeId: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    useDay: [
      { required: true, message: "日期不能为空", trigger: "blur" }
    ],
    planId: [
      { required: true, message: "固定发车方案ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询排班列表 */
function getList() {
  loading.value = true;
  listSchedulingDaily(queryParams.value).then(response => {
    schedulingDailyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

watch(() => form.value.useDay, (newValue, oldValue) => {
  if (newValue) {
    console.log('sum的值变化了', newValue, oldValue)
    getPlanListByDay(newValue).then(res => {
      planDatas.value = res.data
    })
  }
})
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    useDay: null,
    routeId: null,
    planId: null,
    status: null,
    deptId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("schedulingDailyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加排班";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getSchedulingDaily(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改排班";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulingDailyRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateSchedulingDaily(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addSchedulingDaily(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除排班编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delSchedulingDaily(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}
getList();
const routeList = ref([]);
function getRoute() {
  getRouteList().then(res => {
    routeList.value = res.rows
  })
}
getRoute()

const schedulingPlanOpen = ref(false);
const schedulingPlanTitle = ref(null);
/** 排班管理 */
function handleList(row) {
  onlyShow.value = false
  schedulingId.value = row.id
  schedulingPlanId.value = row.planId
  schedulingPlanTitle.value = row.planName
  schedulingPlanOpen.value = true

}

const onlyShow = ref(false);
//发车时刻表
function onlyShowFunc(row) {
  onlyShow.value = true
  schedulingId.value = row.id
  schedulingPlanId.value = row.planId
  schedulingPlanTitle.value = row.planName
  schedulingPlanOpen.value = true
}

function disabledDateFun(time) {
  if (time.getTime() < (new Date().getTime() - 86400000)) {
    return true;
  } else {
    return false;
  }
};

</script>
